import { Injectable, Logger } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { CreateUserDTO, EditUserDTO } from './user.dto';
import { User } from './user.interface';

@Injectable()
export class UserService {
  constructor(@InjectModel('Users') private readonly userModel: Model<User>) {}

  // 查找所有用户
  async findAll(): Promise<User[]> {
    Logger.log('UserService.findAll 方法被调用');
    const users = await this.userModel.find();
    return users;
  }

  // 查找单个用户
  async findOne(_id: string): Promise<User> {
    Logger.log(`UserService.findOne 方法被调用，参数：${_id}`);
    const user = await this.userModel.findById(_id);
    Logger.log('UserService.findOne 方法执行结果：', user);
    return user;
  }

  // 新增单个用户
  async addOne(body: CreateUserDTO): Promise<boolean> {
    Logger.log('UserService.addOne 方法被调用，参数：', body);
    const result = await this.userModel.create(body);
    return Boolean(result);
  }

  // 编辑单个用户
  async editOne(_id: string, body: EditUserDTO): Promise<boolean> {
    Logger.log(
      `UserService.editOne 方法被调用，参数：id:${_id}，DTO:${JSON.stringify(
        body
      )}`
    );
    const result = await this.userModel.findByIdAndUpdate(_id, body);
    return Boolean(result);
  }

  // 删除单个用户
  async deleteOne(_id: string): Promise<boolean> {
    Logger.log(`UserService.deleteOne 方法被调用，参数：id：${_id}`);
    const result = await this.userModel.findByIdAndDelete(_id);
    return Boolean(result);
  }
}
